import React, { FC, useEffect } from 'react'
import { Button, Checkbox, Form, Input, message } from 'antd'
import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Link, useNavigate } from 'react-router-dom'
import { REGISTER_PATHNAME, MANAGE_INDEX_PATHNAME } from '../../router'
import { useRequest } from 'ahooks'
import { loginService } from '../../services/user'
import { setToken } from '../../utils/user-token'
import styles from './index.module.scss'

const USERNAME_KEY = 'USERNAME'
const PASSWORD_KEY = 'PASSWORD'
// 记住密码
function rememberUser(username: string, password: string) {
  localStorage.setItem(USERNAME_KEY, username)
  localStorage.setItem(PASSWORD_KEY, password)
}
// 删除密码
function deleteUserFromStorage() {
  localStorage.removeItem(USERNAME_KEY)
  localStorage.removeItem(PASSWORD_KEY)
}
// 在缓存中读取密码
function getUserInfoFromStorage() {
  return {
    username: localStorage.getItem(USERNAME_KEY),
    password: localStorage.getItem(PASSWORD_KEY),
  }
}
// 登陆失败
const onFinishFailed = (errorInfo: unknown) => {
  console.log('Failed:', errorInfo)
}

const Login: FC = () => {
  const nav = useNavigate()
  const [form] = Form.useForm()
  const { run } = useRequest(
    async values => {
      const { username, password } = values
      const data = await loginService(username, password)
      return data
    },
    {
      manual: true,
      onSuccess(result) {
        const { token = '' } = result
        setToken(token)
        nav(MANAGE_INDEX_PATHNAME)
        message.success('登录成功')
      },
    }
  )
  const onFinish = (values: any) => {
    const { username, password, remember } = values || {}
    run(values)
    if (remember) {
      rememberUser(username, password)
    } else {
      deleteUserFromStorage()
    }
  }
  useEffect(() => {
    const { username, password } = getUserInfoFromStorage()
    console.log('username', username)
    console.log('password', password)
    form.setFieldsValue({ username, password })
  }, [])
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.contentLeft}>
          <div className={styles.logo}>
            <img src={require('../../assets/image/avatar.png')} alt="" />
          </div>
        </div>
        <div className={styles.contentRight}>
          <h1>欢迎回来</h1>
          <Form
            form={form}
            name="basic"
            wrapperCol={{ span: 24 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
              <Input
                className={styles.inputItem}
                prefix={<UserOutlined />}
                placeholder="请输入用户名"
              />
            </Form.Item>
            <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
              <Input.Password
                className={styles.inputItem}
                prefix={<LockOutlined />}
                placeholder="请输入密码"
              />
            </Form.Item>

            <div className={styles.registerBtn}>
              <Button className={styles.registerBtn} type="primary" htmlType="submit">
                登录
              </Button>
            </div>
            <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 1, span: 22 }}>
              <div className={styles.registerBottom}>
                <Checkbox> 记住密码</Checkbox>
                <Link to={REGISTER_PATHNAME}>注册用户</Link>
              </div>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default Login
